package com.lu.dao.impl;

import com.lu.dao.BaseDao;
import com.lu.dao.CommentDao;
import com.lu.entity.Comment;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CommentDaoImpl extends BaseDao implements CommentDao {
    @Override
    public List<Comment> getSomeComments(int cnid) {
        List<Comment> list = new ArrayList<>();
        Connection con = null;
        PreparedStatement pstmt = null;
        String sql = "select * from Comments where cnid=?";
        ResultSet rs = null;

        try {
            con = getCon();
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1,cnid);
            rs = pstmt.executeQuery();
            while (rs.next()){
                int cid = rs.getInt("cid");
                String ccontent = rs.getString("ccontent");
                Date cdate = rs.getDate("cdate");
                String cip = rs.getString("cip");
                String cauthor = rs.getString("cauthor");
                Comment comment = new Comment(cid,cnid,ccontent,cdate,cip,cauthor);
                list.add(comment);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            closeAll(con,pstmt,rs);
        }

        return list;
    }

    @Override
    public int insertOneComment(Comment comment) {
        String sql = "insert into Comments (cnid,ccontent,cdate,cip,cauthor) value(?,?,NOW(),?,?)";
        Object[] params = new Object[]{comment.getCnid(),comment.getCcontent(),comment.getCip(),comment.getCauthor()};
        return executeUpdate(sql,params);
    }
}
